class Order < ApplicationRecord
  enum state: [:pending, :checkouted, :sent, :completed, :cancel]
  enum pay_method: [:wepay, :alipay, :moneybag, :cash]

  belongs_to :shop
  belongs_to :user
  belongs_to :logistics_company, optional: true

  has_many :order_items, :dependent => :destroy
  has_many :user_coupons
  has_many :express_tracks, :dependent => :destroy

  def send_notify(name, page_type = '', page_url = '', params = '')
    Notification.create(
      name: name,
      user_id: self.user_id,
      state: :unread,
      page_type: page_type,
      page_url: page_url,
      params: params,
    )
  end
  
  def to_evaluated
    to_e = true
    self.order_items.each do |order_item|
      to_e = order_item.is_evaluated
      if not to_e
        break
      end
    end
    update_column("is_evaluated", to_e)
  end

  def compute_bonus
    bonus = 0.0
    self.order_items.each do |order_item|
      if order_item.spu.presence
        bonus += order_item.fee * order_item.quantity * order_item.spu.bonus / 100
      end
    end
    self.user.update(moneybag: self.user.moneybag + bonus)
  end
  
end
